package com.iyue.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iyue.sso.bean.SSOInfo;
import com.iyue.sso.helper.SSOUtil;

/**
 * 
 * 
 * @author luozm
 * @version $Id: LoginFilter.java,v 1.2 2010/12/17 14:28:04 fresh Exp $
 */
public final class LoginFilter implements Filter {

	private FilterConfig filterConfig = null;

	public void destroy() {
		filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		if (filterConfig == null) {
			return;
		}

		if (request instanceof HttpServletRequest
				&& response instanceof HttpServletResponse) {
			autoLogin((HttpServletRequest) request,
					(HttpServletResponse) response);
		}

		chain.doFilter(request, response);
	}

	private void autoLogin(HttpServletRequest request,
			HttpServletResponse response) {
		SSOInfo info = SSOUtil.auto(request, response);
		if (info != null) {
			request.setAttribute("SSO", info);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
}
